package com.woniuxy.mqconsumer.mqlistener;


import com.rabbitmq.client.Channel;
import com.woniuxy.mqconsumer.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Random;

@Component
@RabbitListener(queues = "send_email_queue")
@Slf4j
public class EmailListenerConsumer {
    @Autowired
    JavaMailSender javaMailSender ;
    @Autowired
    RedisUtils redisUtils ;
    // 消息队列的消费者
    @RabbitHandler
    public void onMsg(Map<String, Object> msg, Channel channel, Message message) throws IOException {
        try {
            for (Map.Entry<String, Object> en : msg.entrySet()){
                System.out.println(en.getKey() +"---"+en.getValue());
            }
            String fromEmail = (String) msg.get("fromEmail");
            String toEmail = (String) msg.get("toEmail");

            SimpleMailMessage emailMessage = new SimpleMailMessage();
            emailMessage.setFrom(fromEmail);
            emailMessage.setTo(toEmail);
            emailMessage.setSubject("注册用户的邮箱验证码");
            String code = this.validateCode();
            emailMessage.setText("您的邮箱验证码是:"+code);

            javaMailSender.send(emailMessage);
            //存储redis
            redisUtils.set(toEmail,code,120);

            //手动回应ack  1. 参数 1 ，获取当前消息的序号  参数 2 ，true  应答 比本消息序号小的 所有消息 false  应该本消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e) {
            e.printStackTrace();
            log.info("消息消费失败 -->"+msg);
            /**
             * 拒绝确认消息:<br>
             * channel.basicNack(long deliveryTag, boolean multiple, boolean requeue) ; <br>
             * deliveryTag:该消息的index<br>
             * multiple：是否批量.true:将一次性拒绝所有小于deliveryTag的消息。<br>
             * requeue：被拒绝的是否重新入队列 <br>
             */
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                    false, true);
        }

    }

    private String validateCode(){
        String data = "0123456789" ;
        String str = "";
        Random random = new Random();
        for (int i=0;i<6;i++){
            //获取 0 --9 随机数
            int k = random.nextInt(10);
            str += data.charAt(k);
        }
        return str ;
    }
}
